package com.learn.security.theory.base64;

import org.apache.commons.codec.binary.Base64;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * Base64加密,解密
 * <p>
 * 算法实现：
 * 1.jdk
 * 2.common codec
 * 3.bouncy castle
 * <p>
 * 应用场景：e-mail，秘钥，证书文件
 */
public class Base64Test {

    private static final String encodeStr = "MyBase64 test";

    public static void main(String[] args) {

        jdkBase64();

        commonsCodesBase64();

        bouncyCastleBase64();

    }

    // 用jdk实现
    private static void jdkBase64() {
        try {
            BASE64Encoder encoder = new BASE64Encoder();
            String encode = encoder.encode(encodeStr.getBytes());
            System.err.println("encode:" + encode);

            BASE64Decoder decoder = new BASE64Decoder();
            System.out.println("decode:" + new String(decoder.decodeBuffer(encode)));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 用Apache的common codes实现
    private static void commonsCodesBase64() {

        byte[] encodeBytes = Base64.encodeBase64(encodeStr.getBytes());
        System.err.println("common codes encode:" + new String(encodeBytes));

        byte[] decodeBytes = Base64.decodeBase64(encodeBytes);
        System.out.println("common codes decode:" + new String(decodeBytes));

    }

    // 用bouncy castle实现
    private static void bouncyCastleBase64() {

        byte[] encodeBytes = org.bouncycastle.util.encoders.Base64.encode(encodeStr.getBytes());
        System.err.println("bouncy castle encode:" + new String(encodeBytes));

        byte[] decodeBytes = org.bouncycastle.util.encoders.Base64.decode(encodeBytes);
        System.out.println("bouncy castle decode:" + new String(decodeBytes));

    }


}
